using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using admin.core.Entities.App;
using admin.core.Repositories;

namespace admin.infrastructure.Repositories
{
    public class AppImageRepository : DapperRepository<AppImage>, IAppImageRepository
    {
        public AppImageRepository(IDbConnection connection) : base(connection)
        {
        }

        public async Task<long> AddImageAsync(AppImage image)
        {
            var sql = @"INSERT INTO ""AppImage"" (""Id"", ""FileName"", ""OriginalFileName"", ""FilePath"", ""FileExtension"", ""FileSize"", ""ContentType"", ""Url"", ""UploadTime"", ""Tags"", ""Description"", ""UserId"", ""IsActived"", ""IsDeleted"", ""CreatedAt"", ""UpdatedAt"", ""CreatedBy"", ""UpdatedBy"", ""Remarks"")
VALUES (@Id, @FileName, @OriginalFileName, @FilePath, @FileExtension, @FileSize, @ContentType, @Url, @UploadTime, @Tags, @Description, @UserId, @IsActived, @IsDeleted, @CreatedAt, @UpdatedAt, @CreatedBy, @UpdatedBy, @Remarks)
RETURNING ""Id"";";
            var id = await Connection.ExecuteScalarAsync<Guid>(sql, image);
            return 1; // 返回成功标识，因为Id已经在image对象中设置了
        }

        public async Task<AppImage> GetByFileNameAsync(string fileName)
        {
            var sql = @"SELECT * FROM ""AppImage"" WHERE ""FileName"" = @FileName AND ""IsDeleted"" = false LIMIT 1;";
            return await Connection.QuerySingleOrDefaultAsync<AppImage>(sql, new { FileName = fileName });
        }

        public async Task<IEnumerable<AppImage>> GetByUserIdAsync(Guid userId)
        {
            var sql = @"SELECT * FROM ""AppImage"" WHERE ""UserId"" = @UserId AND ""IsDeleted"" = false;";
            return await Connection.QueryAsync<AppImage>(sql, new { UserId = userId });
        }

        public async Task<IEnumerable<AppImage>> GetByTagsAsync(string tags)
        {
            var sql = @"SELECT * FROM ""AppImage"" WHERE ""Tags"" LIKE @Tags AND ""IsDeleted"" = false;";
            return await Connection.QueryAsync<AppImage>(sql, new { Tags = $"%{tags}%" });
        }

        public async Task<bool> ExistsByFileNameAsync(string fileName)
        {
            var sql = @"SELECT COUNT(1) FROM ""AppImage"" WHERE ""FileName"" = @FileName AND ""IsDeleted"" = false;";
            var count = await Connection.ExecuteScalarAsync<int>(sql, new { FileName = fileName });
            return count > 0;
        }

        // 可选：批量根据用户ID数组查询图片（如需仓储层复用，可实现）
        // public async Task<IEnumerable<AppImage>> GetByUserIdsAsync(IEnumerable<Guid> userIds)
        // {
        //     var sql = @"SELECT * FROM \"AppImage\" WHERE \"UserId\" = ANY(@UserIds) AND \"IsDeleted\" = false;";
        //     return await Connection.QueryAsync<AppImage>(sql, new { UserIds = userIds.ToArray() });
        // }

        // 可扩展图片相关的特殊数据访问方法
    }
} 